package tenglang.common.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnJava;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Configuration
@EnableConfigurationProperties({DruidDataSourceProperties.class})
@ConditionalOnClass(DruidDataSource.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.alibaba.druid.pool.DruidDataSource", matchIfMissing = false)
@EnableTransactionManagement // 系统开始事务
public class DruidAutoConfiguration{
	
	@SuppressWarnings("unchecked")
    protected <T> T createDataSource(DataSourceProperties properties,
                                     Class<? extends DataSource> type) {
		return (T) properties.initializeDataSourceBuilder().type(type).build();
	}

	@Autowired
	private DataSourceProperties dataSourceProperties;
	@Autowired
	private DruidDataSourceProperties druidDataSourceProperties;
	@Autowired
	private Environment environment;



	 @Bean("dataSource")
	 public DruidDataSource dataSource() {
		 JdbcConfig jdbcConfig=jdbcConfig();
		 dataSourceProperties.setUrl(jdbcConfig.getMaster().getUrl());
		 dataSourceProperties.setUsername(jdbcConfig.getMaster().getUsername());
		 dataSourceProperties.setPassword(jdbcConfig.getMaster().getPassword());
		 DruidDataSource dataSource = createDataSource(
				 dataSourceProperties, DruidDataSource.class);

		 dataSource.configFromPropety(druidDataSourceProperties.toProperties());
		 DatabaseDriver databaseDriver = DatabaseDriver.fromJdbcUrl(dataSourceProperties.determineUrl());
		 String validationQuery = databaseDriver.getValidationQuery();
		 if (validationQuery != null) {
	            dataSource.setTestOnBorrow(true);
	            dataSource.setValidationQuery(validationQuery);
	     }
		 return dataSource;
	 }

	/**
	 * 分页插件
	 */
	@Bean
	@ConditionalOnClass(name={"com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"})
	@ConditionalOnProperty(name = "baomidou.enabled")
	public Object paginationInterceptor() {
		return new PaginationInterceptor();
	}



	 public JdbcConfig jdbcConfig(){
		    JdbcConfig jdbcConfig=new JdbcConfig();
		    jdbcConfig.setMaster(new JdbcConfig());
		    jdbcConfig.getMaster().setUrl(environment.getProperty("jdbc.config.master.url"));
		    jdbcConfig.getMaster().setPassword(environment.getProperty("jdbc.config.master.password"));
		    jdbcConfig.getMaster().setUsername(environment.getProperty("jdbc.config.master.username"));
            return jdbcConfig;
	 }

	    @Bean
	    public ServletRegistrationBean druidStatViewServlet(@Autowired DruidDataSourceProperties druidDataSourceProperties) {
	        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
	    }
	   
	    @Bean
	    public FilterRegistrationBean druidWebStatFilter() {
	        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
	        //添加过滤规则.
	        filterRegistrationBean.addUrlPatterns("/*");
	        //添加不需要忽略的格式信息.
	        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
	        return filterRegistrationBean;
	    }

}
